package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.dao.*;
import com.entrogy.service.CourseService;
import com.entrogy.service.PositionService;
import com.entrogy.utils.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class CourseServiceImpl implements CourseService {

	private static final Logger logger = LoggerFactory.getLogger(CourseServiceImpl.class);

	@Autowired
	private CourseMapper courseMapper;//课程管理 dao接口

	@Autowired
	private ClassMapper classMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private PositionService positionService;

	@Autowired
	private DepartmentMapper departmentMapper;

	@Autowired
	private UtilsMapper utilsMapper;

	/**
	 *  新增课程
	 * @param
	 * @param gradeId
	 * @param courseTotalScore
     * @return int
	 */
	@Override
	public int addCourse(String courseName, int classId, String schoolCode, int courseId, int staticCourseId, Integer gradeId, Double courseTotalScore) {
		return courseMapper.addCourse(courseName,classId,schoolCode,courseId,staticCourseId,gradeId,courseTotalScore);
	}

	/**
	 * 修改课程
	 * @param
	 * @return int
	 */
	@Override
	public int updateCourse(int id,String courseName,String course_id) {
		return courseMapper.updateCourse(id,courseName,course_id);
	}

	/**
	 *  获取课程信息列表
	 * @param
	 * @return List
	 */
	@Override
	public List<CourseEntity> getCourseList(String courseName,String gradeId,String classId,String schoolCode) {
		return courseMapper.getCourseList(courseName,gradeId,classId,schoolCode);
	}

	/**
	 *  获取课程信息列表
	 * @param id
	 * @return  int
	 */
	@Override
	public int deleteCourse(int id,String schoolCode) {
		return courseMapper.deleteCourse(id,schoolCode);
	}

	/**
	 *  条件获取列表总数
	 * @param
	 * @return int
	 */
	@Override
	public int  getTotal(String courseName,String gradeId,String classId,String schoolCode){
		return courseMapper.getTotal(courseName,gradeId,classId,schoolCode);
	}


	@Override
	public int accountAssignment(String[] courseId, String teacherId,String schoolCode,int type) {
		/**
		 *给教师分配课程流程：
		 * 1.先根据该教师要分配的课程ID 去查询出对应所分配的所有教师，
		 * 2.去判断除了该教师外 如果有其他教师则给其课程在加一位教师，如果只有该教师 则不去改变，如果没有分配教师则分配该教师
		 */
		  int code = 0;
	 if(type==2){
		List<CourseEntity>   list1=courseMapper.getTeacherId(schoolCode);
		for (CourseEntity courseEntity:list1){
			if (StringUtils.isNoneBlank(courseEntity.getTeacherId())) {
				if (courseEntity.getTeacherId().contains(teacherId)) {
					courseMapper.updateTeacherId(courseEntity.getId(), setTeacherId(courseEntity.getTeacherId(), teacherId));
				}
			}
		}
	  }

		if (courseId.length > 1) {
			for (int i = 0; i < courseId.length; i++) {
				//根据课程id查询班级id，然后截取班级id拼接0000即可得到年级id
				Integer classId = courseMapper.findClassIdByCourseId(courseId[i]);
				Integer gradeId = Integer.valueOf(classId.toString().substring(0,3) + "0000");
				code = accountAssignmentMethod(courseId[i], schoolCode, teacherId, gradeId);
			}
		} else {
			Integer classId = courseMapper.findClassIdByCourseId(courseId[0]);
			Integer gradeId = Integer.valueOf(classId.toString().substring(0,3) + "0000");
			code = accountAssignmentMethod(courseId[0], schoolCode, teacherId, gradeId);
		}
		  return code;
	}

	private  String  setTeacherId(String TeacherId,String teacherId1){
		String[] ms=TeacherId.split(",");
		List<String> stringB = Arrays.asList(ms);
		List<String> list1=new ArrayList<>();
		for (String string : stringB) {
			if (!string.equals(teacherId1)){
				list1.add(string);
			}
		}
		String m = String.join(",", list1);
		return m;
	}
	@Override
	public List<UserEntity> getUserAccount(String schoolCode) {
		return courseMapper.getUserAccount(schoolCode);
	}

	@Override
	public int updateUserAccount(String courseId, String teacherId, String schoolCode) {
		/**
		 *编辑教师的课程：
		 * 1.查询出该教师所教的所有课程
		 * 2.先判断该教师有没有课程分配了，如果没有 则查询出该教师所教的所有课程 归零
		 * 3.如果该教师有分配的课程，则遍历查询出来所教的所有课程，看那一门没有 归零，
		 * 4.遍历给其分配的课程 看再历史课程中有没有该课程 如果没有 则新增一位教师
		 */
		int code = 0;
		List<CourseEntity> courseEntities = courseMapper.getCourseByTeacherId(teacherId,schoolCode);
		if(StrUtils.isNullOrEmpty(courseId)){//没有分配课程了  TODO 需要断点测试-------------------------------------
            for (CourseEntity courseEntity:courseEntities){
            	String teacherIdDB = courseEntity.getTeacherId();
            	if(teacherIdDB.contains(",")){//还有其他老师
					if(teacherIdDB.startsWith(teacherId)){
						teacherIdDB = teacherIdDB.substring(teacherId.length(),teacherIdDB.length()); //刚开始的位置
					}else if(teacherIdDB.endsWith(teacherId)){
						teacherIdDB = teacherIdDB.substring(0,teacherIdDB.length()-teacherId.length()); //最后的位置
					}else{//中间位置
						teacherIdDB = teacherIdDB.substring(0,teacherIdDB.indexOf(teacherId))+teacherIdDB.substring(teacherIdDB.lastIndexOf(teacherId),teacherIdDB.length()-1);
					}

				}else{
					teacherIdDB = "";
				}
				//根据课程id查询班级id，然后截取班级id拼接0000即可得到年级id
				Integer classId = courseMapper.findClassIdByCourseId(courseEntity.getId() + "");
				Integer gradeId = Integer.valueOf(classId.toString().substring(0,3) + "0000");
				code = courseMapper.accountAssignment(courseEntity.getId(),teacherIdDB,schoolCode, gradeId);
			}
		}
		return code;
	}

	@Override
	public int insertStaticCourse(String courseName, String uid, String schoolCode) {
		return courseMapper.insertStaticCourse(courseName,uid,schoolCode);
	}

	@Override
	public int updateStaticCourse(int id, String courseName, String uid, String schoolCode) {
		return courseMapper.updateStaticCourse(id,courseName,uid,schoolCode);
	}

	@Override
	public List<StaticCourseEntity> getStaticCourse(String schoolCode) {
		return courseMapper.getStaticCourse(schoolCode);
	}

	@Override
	public List<String> getStaticCourseName(String schoolCode) {
		return courseMapper.getStaticCourseName(schoolCode);
	}


	private int accountAssignmentMethod(String strCourseId,String schoolCode,String teacherId, Integer gradeId){
		int cId = Integer.parseInt(strCourseId);
		String teacherIdDB = courseMapper.getCourseById(cId,schoolCode);
		if(!StrUtils.isNullOrEmpty(teacherIdDB)){ //有分配的教师
			try {
				if (!teacherIdDB.contains(teacherId)){
					teacherId = teacherIdDB+","+teacherId;//给该科目再分配一个老师
				}
			}catch (Exception e){
                  e.printStackTrace();
				  return  0;
			}
		}
		return courseMapper.accountAssignment(cId,teacherId,schoolCode,gradeId);
	}

	/**
	 *  获取某个学校的课程ID
	 * @param schoolCode
	 * @return
	 */
    @Override
	public List<Integer> getIdBySchoolCode( String schoolCode){
		return courseMapper.getIdBySchoolCode(schoolCode);
	};




	/**
	 *  根据id 查询课程名称
	 * @return
	 */
	@Override
	public String getCourseNameById(String schoolCode,Integer staticCourseId){
		return courseMapper.getCourseNameById(schoolCode,staticCourseId);
	};

	/**
	 *   查询用户信息分页
	 * @param schoolCode
	 * @return
	 */
	@Override
	public List<Map<String,Object>>  getUserList(String schoolCode,String name){
		List<Map<String,Object>> list=courseMapper.getUserList(schoolCode,name);
		List<CourseEntity>   list1=courseMapper.getTeacherId(schoolCode);
		List<Map<String,Object>> list3=new ArrayList<>();
		for (Map map1:list) {
			String cName="";
			String  id=map1.get("id").toString();//教师id
			if (list1!=null){
				for (CourseEntity courseEntity:list1){
					if (courseEntity.getTeacherId()!=null){
						if (courseEntity.getTeacherId().contains(id)){
							cName+=courseEntity.getCourseName()+",";
						}
					}

				}
			}
			map1.put("cName",cName);
			list3.add(map1);
		}
		return list3;
	};
	/**
	 *   查询用户信息总数
	 * @param schoolCode
	 * @return
	 */
	@Override
	public int  getUserListTotal(String schoolCode,String name){
		return courseMapper.getUserListTotal(schoolCode,name);
	};


	/**
	 *  获取教师id
	 * @param schoolCode
	 * @return
	 */
	@Override
	public List<CourseEntity>  getTeacherId(String schoolCode){
		return courseMapper.getTeacherId(schoolCode);
	};

	/**
	 *  清楚老师所教课程
	 * @return
	 */
	@Override
	public int  clearCourse(String teacherId,String schoolCode){
		//
		int code = 0;
		List<CourseEntity> list1 = courseMapper. getTeacherId(schoolCode);
		for (CourseEntity courseEntity : list1){
			if (StringUtils.isNoneBlank(courseEntity.getTeacherId())){
				if (courseEntity.getTeacherId().contains(teacherId)){
					code = courseMapper.updateTeacherId(courseEntity.getId(), setTeacherId(courseEntity.getTeacherId(), teacherId));
				}
			}
		}
		return code;
	}

	/**
	 * 根据年级查询所有课程
	 * @param gradeId
	 * @param schoolCode
	 * @return
	 */
	@Override
	public List<StaticCourseEntity> getCourseListByGradeId(String gradeId, Integer schoolCode) {
		return courseMapper.getCourseListByGradeId(gradeId,schoolCode);
	}

	@Override
	public boolean hasFinishAssignCourse(String gradeId, List<StaticCourseEntity> staticCourseList, Integer schoolCode) {
		List<ClassEntity> classList = classMapper.getClassListByGradeId(Integer.valueOf(gradeId), schoolCode);
		List<ClassAndCourseEntity> classAndCourseList = new ArrayList<>();
		for (int i = 0; i < classList.size(); i++) {
			int classId = classList.get(i).getId();
			//查询一个班级所拥有的静态科目
			List<Integer> staticCourseIds = courseMapper.listStaticCourseByClassId(classId, schoolCode);
			ClassAndCourseEntity temp = new ClassAndCourseEntity();
			temp.setClassId(classId).setStaticCourseIds(staticCourseIds);
			classAndCourseList.add(temp);
		}
		//两两比较每个班的科目
		for (int i = 0; i < classAndCourseList.size(); i++) {
			for (int j = 0; j < classAndCourseList.size(); j++) {
				if (i == j){
					continue;
				}
				List<Integer> staticCourseIdsOut = classAndCourseList.get(i).getStaticCourseIds();
				List<Integer> staticCourseIdsIn = classAndCourseList.get(j).getStaticCourseIds();
				Collections.sort(staticCourseIdsOut);
				Collections.sort(staticCourseIdsIn);
				if (!staticCourseIdsOut.equals(staticCourseIdsIn)){
					return false;
				}
			}
		}
		return true;
	}

	@Override
	public List<StaticCourseEntity> listStaticCourse(Integer schoolCode) {
		return courseMapper.listStaticCourse(schoolCode);
	}

	@Override
	public boolean initCourseData(Integer schoolCode, Integer gradeId, Integer classId) {
		// 新建静态课程
		List<String> staticCourseList = utilsMapper.listCourseNameByExcel(schoolCode);
		int insertStaticCourseRow = utilsMapper.insertStaticCourse(schoolCode, staticCourseList);
		Set<String> teacherIdSet = new HashSet<>();
		List<JSONObject> excelData = courseMapper.listCourseExcelData(schoolCode, gradeId, classId);
		for (JSONObject row : excelData) {
			schoolCode = row.getInteger("schoolCode");
			String teacherName = row.getString("teacherName");
			String gradeName = row.getString("gradeName");
			String grade_id = classMapper.getClassId(schoolCode, gradeName);
			Integer classOrder = row.getInteger("classId");
			String class_id = (classOrder < 10 ? grade_id.substring(0, 4) : grade_id.substring(0, 3)) + classOrder + "00";
			Integer static_course_id = courseMapper.getStaticCourseId(schoolCode, row.getString("courseName"));
			String course_id = class_id.substring(0,5) + static_course_id;
			String staticCourseName = courseMapper.getCourseNameById(String.valueOf(schoolCode), static_course_id);
			ClassEntity classEntity = classMapper.getClassById(Integer.valueOf(class_id), schoolCode);
			String course_name = classEntity.getClassName() + staticCourseName;
			String teacher_id = null;
			if (StringUtils.isNoneBlank(teacherName)){
				teacher_id = userMapper.getUserId(schoolCode, null, null, teacherName);
				teacherIdSet.add(teacher_id);
			}
			courseMapper.insertCourse(course_id, course_name, class_id, schoolCode, grade_id, teacher_id, static_course_id);

		}
		// 分配任课老师的职位
		Map<String, Object> params = new HashMap<>();
		params.put("school_code", schoolCode);
		params.put("department_name", "通用部门");
		List<Map<String, Object>> maps = departmentMapper.selectDepartmentByT(params);
		if (maps.size() == 0){
			logger.error("通用部门不存在，课程信息录入失败！");
			throw new RuntimeException();
		}
		for (String teacher_id : teacherIdSet) {
			List<PositionEntity> positionList = new ArrayList<>();
			PositionEntity positionEntity = new PositionEntity();
			positionEntity.setSid(17);
			positionEntity.setDid((Integer) maps.get(0).get("department_id"));
			positionList.add(positionEntity);
			positionService.InsertUserPositionInfos(teacher_id, positionList);
		}
		return true;
	}

	@Override
	public List<CourseEntity> listTeacherCourse(String teacherId) {
		return courseMapper.listTeacherCourse(teacherId);
	}

}
